<?php
// Tim'Roster
// Copyright (c) 2011 Nicolas Nallet <aspgic2@gmail.com>
//
// This file is part of Tim'Roster.
//
// Tim'Roster is free software; you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Tim'Roster is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

session_start();

$xml_config = simplexml_load_file('config.xml');

include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/technical_class/authentification/User.php');
include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/technical_class/language/language.php');
include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/class/Guild.php');
include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/class/Character.php');
include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/technical_class/error/Error_Log.php');
require_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/external_libraries/ryzom_api/ryzom_api.php');
include_once($_SERVER["DOCUMENT_ROOT"].$xml_config->roster_root_directory.'/render/render_header_footer.php');



if (!User::is_user_logged()){
    User::store_url_referer();
    header('Location: login.php');
}

$content = '';

if ((isset($_GET['update']))&&((int)$_GET['update'] == 1)) {

    if ((!User::is_user_authorize(User::ADMIN_GROUP_ID))) {
        header('Location: unauthorized_access.php');
    }
    else {
        if ((isset($_GET['cid'])) && (is_numeric($_GET['cid']))){
            
            $c = Character::get_character_api_key($_GET['cid']);
            if ((isset($c[0])) && (isset($c[2]))){
                $content .= extract_user_API_data(ryzom_decrypt($c[0]), $c[0], $_GET['cid'], $c[2]);
            }
        }
        else {
            if ((isset($_GET['gid'])) && (is_numeric($_GET['gid']))){

                $g = Guild::get_guild($_GET['gid']);
                if ((isset($g[0])) && (isset($g[2]))){
                    $content .= extract_guild_API_data(ryzom_decrypt($g[0]), $_GET['gid'], $g[2]);
                }
            }
            else {
                //retrieve user data
                $char_keys = Character::get_all_api_key();
                
                if (isset($char_keys)){
                    foreach ($char_keys as $pair) {
                        $content .= extract_user_API_data(ryzom_decrypt($pair[0]), $pair[0], $pair[1], $pair[2]);
                    }
                }

                //retrieve guild data
                $guild_keys = Guild::get_all_api_key();

                if (isset($guild_keys)){
                    foreach ($guild_keys as $pair) {
                        $content .= extract_guild_API_data(ryzom_decrypt($pair[0]), $pair[1], $pair[2]);
                    }
                }
            }
        }

        $content .= Language::get_instance()->get_label('lb_update_complete').'<br/>';
    }
}

else {
    if(isset($_POST['key']) && $_POST['key'] != '') {
        //echo '<meta http-equiv="refresh" content="0;URL=update_data.php?ckey='.ryzom_encrypt($_POST['key']).'">';
        header('Location: update_data.php?ckey='.ryzom_encrypt($_POST['key']).'');
    }

    if (isset($_GET['ckey']) && $_GET['ckey'] != '') {

            // Display the profile
            $ckey = $_GET['ckey'];
            $key = ryzom_decrypt($ckey);

            $gid=0;
            if(ryzom_guild_valid_key($key, $gid)) {
                $xml = ryzom_guild_simplexml($key);

                if (!Guild::exists($key, false)){

                    $guild = new Guild();
                    $guild->deserialize($xml, $ckey, null);

                    $content .= Language::get_instance()->get_label('lb_guild_saved').'<br/>';
                }
                else {
                    $content .= Language::get_instance()->get_label('lb_guild_already_in_db').'<br/>';
                }
            }
            else {

                $uid=0;$slot=0;$full=false;
                if(ryzom_character_valid_key($key, $uid, $slot, $full)) {

                    $xml = ryzom_character_simplexml($key, 'full');

                    if (Character::exists($key, $xml->name, false)){

                        $character = new Character();
                        $character->deserialize($xml, $ckey, null);

                        $content .= Language::get_instance()->get_label('lb_character_saved').'<br/>';
                    }
                    else {
                        $content .= Language::get_instance()->get_label('lb_character_not_in_db').'<br/>';
                    }
                }
                else {
                    $content .= Language::get_instance()->get_label('lb_invalid_api_key').'<br/>';
                }
            }

            if($xml->getName() == 'error') {
                    $content .= Language::get_instance()->get_label('lb_error').' : '.$xml.'<br/>';
            }

    } else {
            // Display the form to enter the API Key
            $content = '<form action="" method="post">';
            $content .= Language::get_instance()->get_label('lb_add_api_key_instruction').'<br/>';
            $content .= '<input type="text" name="key"><br/>';
            $content .= '<input type="submit" value="'.Language::get_instance()->get_label('lb_submit').'" />';
            $content .= '</form>';
    }
}

function extract_user_API_data($decrypted_API_key, $encrypted_key, $char_id, $char_name){
    $log = '';
    
    //exclude api key generate by the roster
    if (Character::is_real_api_key($decrypted_API_key, false)){

        $xml = ryzom_character_simplexml($decrypted_API_key, 'full');

        if($xml->getName() == 'error') {
            $error = new Error_Log(null, Error_Log::API_DATA_EXTRACT_ERROR_ID,
                    date('Y-m-d H:i:s',time()), $char_id, null, null, Error_Log::CHARACTER_ENTITY_TYPE);
            $error->save_error_log();

            $log .= '<b>'.Language::get_instance()->get_label('lb_fail_to_update_character_data').' : '.$char_name.'</b><br/>';
        }
        else {
            $char = new Character();
            $char->deserialize($xml, $encrypted_key, $char_id);
            $log .= Language::get_instance()->get_label('lb_update_character_data_complete').' : '.$char->get_name().'<br/>';
        }
    }

    return $log;
}

function extract_guild_API_data($decrypted_API_key, $guild_id, $guild_name){   
    $xml = ryzom_guild_simplexml($decrypted_API_key);
    $log = '';

    if($xml->getName() == 'error') {
        $error = new Error_Log(null, Error_Log::API_DATA_EXTRACT_ERROR_ID, date('Y-m-d H:i:s',time()), $guild_id, null, null,  Error_Log::GUILD_ENTITY_TYPE);
        $error->save_error_log();
        $log .= '<b>'.Language::get_instance()->get_label('lb_fail_to_update_guild_data').' : '.$guild_name.'<br/>';
    }
    else {
        $guild = new Guild();
        $guild->deserialize($xml, $decrypted_API_key, $guild_id);
        $log .= Language::get_instance()->get_label('lb_update_guild_data_complete').' : '.$guild->get_name().'<br/>';
    }

    return $log;
}

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script type="text/javascript" src="external_libraries/jquery-ui/js/jquery-1.4.4.min.js"></script>
        <script type="text/javascript" src="external_libraries/jquery-ui/js/jquery-ui-1.8.7.custom.min.js"></script>
        <script type="text/javascript" src="js/menudialog.js"></script>
        <link rel="shortcut icon" type="images/x-icon" href="img/quest_jeton.png" />

        <style>
            @import url(css/base.css);
            @import url(external_libraries/jquery-ui/css/smoothness/jquery-ui-1.8.6.custom.css);
        </style>
    </head>
    <body>
        <center>
            <?php
                echo render_page_header().'</br>';
            ?>
            <table>
                <tr>
                    <td valign="top"><?php echo include('menu.php'); ?></td>
                    <td valign="top">
                        <fieldset>
                            <h1 class="title">
                                <?php
                                    if ((isset($_GET['update']))&&((int)$_GET['update'] == 1)) {
                                        echo Language::get_instance()->get_label('lb_update_data');
                                    }
                                    else {
                                        echo Language::get_instance()->get_label('lb_add_api_key');
                                    }
                                ?>
                            </h1>
                            <?php
                                echo $content;
                            ?>
                        </fieldset>
                   </td>
                </tr>
            </table>
            <?php
                echo render_page_footer();
            ?>
        </center>
    </body>
</html>
